import { ComponentClass } from 'react'
import Taro, { Component, Config } from '@tarojs/taro'
import { AtList, AtListItem, AtAvatar, AtButton } from 'taro-ui'
import { View, Image, Text, Button } from '@tarojs/components'
import { connect } from '@tarojs/redux'
import XPage from '../../components/XPage'
import cloverIcon from '../../assets/cloverActive@2x.png'
import myTo2x from './my@2x.png'
import { fetchUser, add, addAddress } from '../../actions/my'
import { prefix, ossPrefix } from '../../utils'
import './index.scss'

type PageStateProps = {
  my: object | {},
}

type PageDispatchProps = {
  fetch: ({number: number}, callbak: object) => void,
  add: ({number: number}, callbak: object) => void,
  addAddress: (object, callbak: object) => void
}

type PageOwnProps = {}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface My {
  props: IProps
}

@connect(({ my }) => ({
  my
}), (dispatch) => ({
  fetch(data, callback) {
    dispatch(fetchUser(data, callback))
  },
  add(data, callback) {
    dispatch(add(data, callback))
  },
  addAddress(data, callback) {
    dispatch(addAddress(data, callback))
  }
}))
class My extends Component {
  config: Config = {
    navigationBarTitleText: '幸运草小程序'
  }

  state = {
    isToastOpened: false,
    isToastTitle: '请先登录！',
    data: {},
    dashboards: {
      amount: 0,
      join: 0,
      launch: 0,
      winning: 0,
    },
  }

  componentWillMount() {
    Taro.getSetting().then(e=>{
      if(e.authSetting['scope.userInfo']) {
        this.props.fetch({number: 0}, data => {
          this.setState(state => ({...state, dashboards: data.data}))
        })
        Taro.getUserInfo().then(userInfo => {
          this.setState(state => ({
            ...state,
            data: userInfo.rawData ? JSON.parse(userInfo.rawData) : {},
          }))
        })
      }
    })
  }

  // 登录
  onGotUserInfo = e => {
    // 第一步 登录成功后获得用户信息
    const data = e.detail.rawData ? JSON.parse(e.detail.rawData) : {}
    // 第二步 保存到 store
    this.setState(state => ({
      ...state,
      data,
    }), () => {
      // 第三步 换取 openId并完成注册
      Taro.login().then((result) => {
        const obj = {}
        Object.assign(obj, result, data, {type: 0})

        Taro.request({
          url: `${prefix}/api/v1/access/weapp`,
          method: 'POST',
          data: obj,
          header: { 'content-type': 'application/json' }
        })
        .then(res => {
          Taro.setStorage({ 
            key: 'userInfo', 
            data: {...data, ...res.data.data, ...result}
          })           
        })
      })
    })
  }

  // 我的页面 - 收获幸运草
  handleIntegralIns = () => {
    Taro.getSetting().then(e=>{
      if(e.authSetting['scope.userInfo']) { 
        this.props.add(({number: 1}), data => {
          if(data.errno) {
            Taro.showToast({ title: '服务器繁忙！', icon: 'none' })
          } else {
            Taro.showToast({ title: data.errmsg, icon: 'success' })
          }
        })
      } else {
        Taro.showToast({ title: '请先点击头像登录！', icon: 'none' })
      }
    })
  }

  handleAddress = () => {
    Taro.getSetting().then(e=>{
      if(e.authSetting['scope.userInfo']) {
        // 提交收货地址
        Taro.chooseAddress()
        .then(addressInfo => {
          this.props.addAddress({addressInfo}, ()=>{
            Taro.showToast({ title: '地址保存成功~', icon: 'none' })
          })
        })
      } else {
        Taro.showToast({ title: '请先登录！', icon: 'none' })
      }
    })
  }

  handleToPage = (pathName, e) => {
    e.stopPropagation()

    Taro.getSetting().then(e=>{
      if(e.authSetting['scope.userInfo']) { 
        Taro.navigateTo({ url: pathName })
      } else {
        Taro.showToast({ title: '请先登录！', icon: 'none' })
      }
    })
  }

  render() {

    const dashboardArray = [{
      number: this.state.dashboards.join,
      title: '全部抽奖',
      pathName: '/pages/my/goods/index'
    }, {
      number: this.state.dashboards.launch,
      title: '发起抽奖',
      pathName: '/pages/my/goods/Launch'
    }, {
      number: this.state.dashboards.winning,
      title: '中奖纪录',
      pathName: '/pages/my/goods/Records'
    }]

    return (
      <XPage>
        <View className='my'>
          <View className='bg'>
            <Image src={myTo2x} mode='widthFix' className='bg-image' />
            <View className='position'>
              <View className='collect'>
                <View className='info'>
                  <Button openType="getUserInfo" onGetUserInfo={this.onGotUserInfo} className="getUserInfo">
                    {
                      this.props.data.avatarUrl
                      ?
                      <AtAvatar circle image={this.props.data.avatarUrl} />
                      :
                      <View className="authorize">登录</View>
                    }
                  </Button>
                  {/* <Image src='https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png' mode='widthFix' className='avatar' /> */}
                  <View className='mine'>
                    <Text className='userName'>{this.props.data.nickName ? this.props.data.nickName : '请先登录'}</Text>
                    {/*<Text className='caption'>&nbsp;&nbsp;我的幸运草 x00</Text>*/}
                  </View>
                </View>
                <View className='progress'>
                  <View className='clover'>
                    {
                      Array.from(new Array(6)).map((item, key) => {
                        return (
                          <View className='cell' key={key}>
                            <Image src={cloverIcon} mode='widthFix' className='clover-icon' />
                          </View>
                        )
                      })
                    }
                  </View>
                  <View className='explain'>
                    <Text className='text'>
                      {/*(4/6) 随时*/} 四叶草每小时产出,每天共24枚,记得收取哦~
                    </Text>
                  </View>
                  <View className='submit'>
                    <AtButton 
                      type='primary'
                      size='small' 
                      className='btn'
                      onClick={this.handleIntegralIns.bind(this)}
                    >收获</AtButton>
                  </View>
                </View>
              </View>
            </View>
          </View>

          <View className='table_1543304811640'>
            {
              dashboardArray.map((item, key) => (
                <View className='cell' key={key} onClick={this.handleToPage.bind(this, item.pathName)}>
                  <Text className='bold'>{item.number}</Text>
                  <Text className='secondary'>{item.title}</Text>
                </View>
              ))
            }
          </View>

        </View>
        <AtList>
          <AtListItem
            title="收货地址"
            arrow='right'
            thumb={ossPrefix + 'icons/position.svg'}
            onClick={this.handleAddress}
          />
          <AtListItem
            title="常见问题"
            arrow='right'
            thumb={ossPrefix + 'icons/question.svg'}
            onClick={this.handleToPage.bind(this, "/pages/my/Questions")}
          />
          <AtListItem
            title="意见反馈"
            arrow='right'
            thumb={ossPrefix + 'icons/feedback.svg'}
            onClick={this.handleToPage.bind(this, "/pages/my/Feedbacks")}
          />
        </AtList>
      </XPage>
    )
  }
}

export default My as ComponentClass<PageOwnProps, PageState>